<?php

namespace app\admin\controller\spider;

use app\common\controller\Backend;
use app\admin\model\spider\Catalogue as catalogueModel;
use app\admin\model\spider\Platform as platformModel;
use app\admin\model\spider\Task as taskModel;

/**
 * 抓取关键字管理
 *
 * @icon fa fa-circle-o
 */
class Keywords extends Backend
{

    /**
     * Keywords模型对象
     * @var \app\admin\model\spider\Keywords
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\spider\Keywords;

    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['platform'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('platform')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function spider($ids = null)
    {
        $list = $this->model->whereIn('id', $ids)->select();
        empty($list) && $this->error("未找到可用数据");

        $catalogueList = [];
        foreach ($list as $row) {
            if (!isset($catalogueList[$row['spider_platform_id']])) {
                $where = [
                    'spider_platform_id' => $row['spider_platform_id'],
                    'switch' => 1,
                ];
                $catalogueList[$row['spider_platform_id']] = catalogueModel::where($where)->select();
            }

            $params = [
                'user_id' => $this->auth->id,
                'platform_id' => $row['spider_platform_id'],
                'updatetime' => time(),
                'createtime' => time(),
            ];
            foreach ($catalogueList[$row['spider_platform_id']] as $catalogueRow) {
                unset($params['task_id']);
                $keywords = urlencode(trim($row['name']));
                $params['get_url'] = str_replace("query=****", "query={$keywords}", $catalogueRow['url']);
                $taskId = (new taskModel)->insertGetId($params);
                $params['task_id'] = $taskId;
                addJob('app\\jobs\\Task', $params, 'task');
            }
        }
        $this->success('操作成功');
    }


    public function ssss()
    {
        $arr = [
            'Akainu (Sakazuki)',
            'Aokiji (Kuzan)',
            'Bartholomew Kuma',
            'Big Mom (Charlotte Linlin)',
            'Boa Hancock',
            'Brook',
            'Buggy',
            'Buggy the Clown',
            'Charlotte Linlin (Big Mom)',
            'Coby',
            'Crocodile',
            'Dracule Mihawk',
            'Edward Newgate (Whitebeard)',
            'Enel',
            'Eustass Kid',
            'Franky',
            'Jewelry Bonney',
            'Jimbei',
            'Jinbe',
            'Kaido',
            'Kizaru (Borsalino)',
            'Magellan',
            'Marshall D. Teach (Blackbeard)',
            'Monkey D. Luffy',
            'Nami',
            'Nico Robin',
            'Portgas D. Ace',
            'Rob Lucci',
            'Roronoa Zoro',
            'Sabo',
            'Sakazuki (Akainu)',
            'Sanji',
            'Sengoku',
            'Shanks',
            'Shirohige (Whitebeard)',
            'Smoker',
            'Tashigi',
            'Tony Tony Chopper',
            'Trafalgar D. Water Law',
            'Usopp',
            'Vinsmoke Ichiji',
            'Vinsmoke Niji',
            'Vinsmoke Reiju',
            'Vinsmoke Yonji',
            'Vivi',
            'Whitebeard (Edward Newgate)',
            'X Drake',
        ];
        $keywords = ' One Piece';
        $new = [];
        foreach ($arr as $k => &$v) {
            $v .= $keywords;
            $new[] = [
                'spider_platform_id' => 1,
                'name' => $v,
            ];
        }
        $this->model->saveAll($new);
        halt(1);
    }

}
